package com.dlz.systemshop.controller;


import com.dlz.systemshop.pojo.APIResponse;
import com.dlz.systemshop.pojo.Category;
import com.dlz.systemshop.pojo.UrlPath;
import com.dlz.systemshop.service.CategoryService;
import com.dlz.systemshop.service.StorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.nio.file.Path;
import java.util.List;

@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    @Autowired
    private StorageService storageService;

    @GetMapping("/deleteById")
    public APIResponse<Void> deleteById(int id) {
        categoryService.deleteById(id);
        return APIResponse.success(null);
    }

    @GetMapping("/list")
    public APIResponse<List<Category>> list() {
        List<Category> categories = categoryService.findAll();
        for (Category category : categories) {
            Integer pid = category.getPid();
            for(Category categoryIn : categories) {
                if(categoryIn.getId().equals(pid)){
                    category.setPname(categoryIn.getName());
                    break;
                }
            }
        }
        return APIResponse.success(categories);
    }

    @GetMapping("/findById")
    public APIResponse<Category> findById(int id) {
        Category category = categoryService.findByid(id);
        return APIResponse.success(category);
    }

    @PostMapping("/add")
    public APIResponse<Void> add(@RequestBody Category category) {
        categoryService.save(category);
        return APIResponse.success(null);
    }
    @PostMapping("/update")
    public APIResponse<Void> update(@RequestBody Category category) {
        categoryService.update(category);
        return APIResponse.success(null);
    }

    @PostMapping("/picture")
    public APIResponse<UrlPath> uploadPicture(@RequestParam("file") MultipartFile file) {
        try {
            Path savedPath = storageService.save(file);
            String relativePath = storageService.getRelativePath(savedPath);
            UrlPath urlPath = new UrlPath();
            urlPath.setUrl("http://localhost:5173/static/image/category/myAdd/"+relativePath);
            urlPath.setSavepath("static/image/category/myAdd/"+relativePath);
            return APIResponse.success(urlPath);
        } catch (RuntimeException e) {
            return APIResponse.error(1000, e.getMessage());
        }
    }
}
